<template>
<div class="UserInfo">
	<!--头像组件-->
<div class="header">
<div><el-avatar ref="icon" shape="square" :size="100" :src="owner.icon" style="margin: 10px 20px;border: 3px solid green;"></el-avatar></div>
<div class="username">{{owner.username}}</div>
</div>


		<!--选项组件-->
<div class="body">
	<!--仅自己使用-->
	<el-button v-if="owner.id==me.id" class="button" @click="iconVisible=true">更换头像</el-button>
	<el-button v-if="owner.id==me.id" class="button" @click="updatePwdVisible=true">修改密码</el-button>
	<!--仅他人使用-->
	<el-button v-if="owner.id!=me.id" class="button" @click="handlerSendRequest(owner.id)">添加好友</el-button>
	<el-button v-if="owner.id!=me.id" class="button"  @click="chatVisible=true;sendMessage=''">发起聊天</el-button>
	<!--都可以使用-->
	<el-button class="button" @click="noteListVisible=true">查看笔记</el-button>
</div>





<!-------------------下面是弹窗页面-------------------------->


<!--修改头像-->
<el-dialog :visible.sync="iconVisible" title="更换头像" center append-to-body width="26%">
	<div class="icon-box">
		<div v-for="(icon,index) in iconData" :key="index" @click="handlerUpdateIcon(icon)">
			<el-avatar shape="square" :size="80" :src="icon.url"  style="border: 3px solid limegreen"></el-avatar>
			<div style="text-align: center;">{{icon.name}}</div>
		</div>
	</div>
</el-dialog>
<!--修改密码弹窗-->
<el-dialog :visible.sync="updatePwdVisible" title="修改密码" center append-to-body width="20%">
	<el-form :model="updatePwdForm" style="width: 320px;">
		<el-form-item>
		<el-input type="text" v-model="updatePwdForm.oldPwd" maxlength="16" placeholder="请输入旧密码"></el-input>	
		</el-form-item>
		<el-form-item>
		<el-input type="text" v-model="updatePwdForm.newPwd" maxlength="16" placeholder="请输入新密码(长度 6~16 位)"></el-input>	
		</el-form-item>
		<el-form-item>
		<el-input type="text" v-model="updatePwdForm.confirmPwd" maxlength="16" placeholder="请再次输入新密码"></el-input>	
		</el-form-item>
		<el-from-item>
			<el-button @click="handlerUpdatePwd" style="margin-left: 50px;">修改</el-button>
			<el-button @click="updatePwdVisible=false" style="margin-left: 50px;">取消</el-button>
		</el-from-item>
	</el-form>
</el-dialog>

		<!--笔记组件弹窗-->
<el-dialog :visible.sync="noteListVisible" width="60%" title="笔记" center append-to-body>
	<NoteList :owner="owner"></NoteList>
</el-dialog>


		<!--聊天组件弹窗-->
<el-dialog :visible.sync="chatVisible" width="40%" :title="'与'+owner.username+'的聊天'" center append-to-body destroy-on-close>
	<div class="chat-box">
		<div class="chat-message" ref="chatMessage">
			<p style="text-align:center;color:darkgray;width: 100%;margin: 15px 0;">--保护隐私信息,谨防网络诈骗--</p>
			<div v-for="message in chatData" :class="getMessageClass(message)">
				<div class="chat-message-icon"><el-avatar  shape="square" :size="70" :src="getMessageIcon(message)"></el-avatar></div>
				<div class="chat-message-content-box">
				<div class="chat-message-created">{{message.created}}</div>
				<div v-if="message.type==1" @click="handlerDownLoad(message.fileId)" class="chat-message-content" style="cursor:pointer;">
					<img :src="require('@/assets/image/file.png')" style="width: 50px;height: 50px;display: inline-block;" />
					<span style="position: relative;">{{message.content}}</span>
					<span style="color:grey;font-size: 12px;position: relative;display: block;">7天内有效</span>
				</div>
				<div v-else class="chat-message-content">{{message.content}}</div>
				</div>
			</div>
			<div style="width:100%;display: block;margin-top: 200px;color:black;float:right;"></div>
		</div>
					<!--聊天文件或表情-->
				<div class="chat-input-type" style="margin: 10px 0;float: right;height: 40px;">
					<img @click="" :src="require('@/assets/image/emo.png')"  
						style="width: 30px;height: 30px;margin-right: 20px;cursor: pointer;display: inline"/>
											
						<!--发送文件--> 
					<el-upload
						style="display: inline-block;"
						action="chat/uploadFile"
						:show-file-list="false"
						auto-upload
						:before-upload="beforeUpload"
						:data="{
							sender:me.id,
							recever:owner.id
						}"
						:headers="headers"
						>
						
					<img @click="" 
						:src="require('@/assets/image/file.png')"  
						style="width: 30px;height: 30px;margin-right: 20px;cursor: pointer;"/>
					</el-upload>
				</div>
		<div class="chat-input">
			<!--聊天输入框-->
			<el-input
				v-model="chatMessageForm.content"
				type="textarea"
				rows="5"
				maxlength="200"
				show-word-limit
				palceholder="快开始聊天吧!"
				class="chat-input-content"
				style="font-size: 15px;"
				></el-input>

				<div class="chat-input-button">
					<el-button @click="sendChatMessage">发送</el-button>
					<el-button @click="chatVisible=false">返回</el-button>
				</div>
			
		</div>
	</div>
</el-dialog>
</div>
</template>

<script>
	import {mapState} from 'vuex'
	import NoteList from './NoteList'
	export default{
		name:'UserInfo',
		data(){
			return{

				noteListVisible:false,
				updatePwdVisible:false,
				iconVisible:false,
				chatVisible:false,
				iconData:[],
				userInfo:{},
				updatePwdForm:{
					id:'',
					oldPwd:'',
					newPwd:'',
					confirmPwd:'',
				},
				filelist:[],
				// 允许的文件类型
				fileType: [ "pdf", "doc", "docx", "xls", "xlsx","txt","png","jpg", "bmp", "jpeg","rar","zip"],
				// 运行上传文件大小，单位 M
				fileSize: 50,
				// 附件数量限制
				fileLimit: 5,
				//请求头
				headers:{
					authorization:localStorage.getItem("token"),
				},
				chatMessageForm:{
					content:'',
					sender:'',
					receiver:'',
					created:'',
				},
				chatData:[],
				getChatDataTimer:null,

			}
		},
		components:{
			NoteList
		},
		props:[
		'ownerId'
		],
		computed:{
			...mapState(['me','owner'])
		},
		methods:{
			beforeUpload(file){
			if (file.type == "" || file.type == null || file.type == undefined){
			this.$message.error("文件类型错误！")	
			return false;
			}
	    	//截取文件的后缀，判断文件类型
			const FileExt = file.name.replace(/.+\./, "").toLowerCase();
			//计算文件的大小
			const isLt5M = file.size / 1024 / 1024 < 20; //这里做文件大小限制
			//如果大于20M
			if (!isLt5M) {
				this.$message.error('上传文件大小不能超过 20MB!');
				return false;
			}
			//如果文件类型不在允许上传的范围内
			if(!this.fileType.includes(FileExt)){
				this.$message.error("不支持上传改文件类型!");
				return false;
		}

			},
			handlerDownLoad(fileId){
				console.log(fileId)
				this.$axios({
					method:'GET',
					url:'chat/downloadFile',
					headers:{
						authorization:localStorage.getItem("token")
					},
					params:{
						fileId:fileId
					},
					responseType:'blob',
				}).then(
					response=>{
						var filename=response.headers.filename;
						console.log("filename->",filename)
						if(filename==null||filename.length<1){
							this.$message.info('文件已经失效')
							return;
						}
						console.log(response.filename)
						let blob = new Blob([response.data], {
                            type: response.data.type
                        });
						 var downloadElement = document.createElement("a");
                            var href = window.URL.createObjectURL(blob); // 创建下载的链接
                            downloadElement.href = href;
                            downloadElement.download = filename; // 下载后文件名
                            document.body.appendChild(downloadElement);
                            downloadElement.click(); // 点击下载
                            document.body.removeChild(downloadElement); // 下载完成移除元素
                            window.URL.revokeObjectURL(href); // 释放掉 blob 对象
					},
					error=>{
						this.$message.info('文件已经失效')
					}
				)
			},
			uploadFile(){
				console.log("纳尼",this.filelist)
			},
			handlerUpdateIcon(icon){
			if(icon.url==this.owner.icon){
				this.$message.info('这是当前头像')
				return;
			}
			this.$confirm('确定修改头像为 '+icon.name,'提示',{
					confirmButtonText:'确定',
					concelButtonText:'取消',
					type:'warning'
				}).then(
					()=>{			
					this.$axios({
						method:'POST',
						url:'user/updateIcon',
						headers:{
							authorization:localStorage.getItem("token")
						},
						data:icon
					}).then(
						response=>{
							if(response.data.success){
								this.owner.icon=icon.url
								this.iconVisible=false
								this.$message.success("修改头像成功")
							}else{
								this.$message.error(response.data.message)
							}
						},
						error=>{
							console.log(error.message)
						}
					)}).catch(
				);
			},
			sendChatMessage(){
				if(this.chatMessageForm.content.length<1){
					this.$message.info('聊天消息不能为空')
					return;
				}
				this.chatMessageForm.sender=this.me.id
				this.chatMessageForm.receiver=this.owner.id
				this.$axios({
					method:'POST',
					url:'chat/sendSolo',
					headers:{
						authorization:localStorage.getItem("token")
					},
					data:this.chatMessageForm
				}).then(
					response=>{
						if(response.data.success){
							this.chatMessageForm.content=''
						}else{
							this.$message.info(response.data.message)
						}
					}
				)
			},
			getChatData(){
				this.$axios({
					method:'POST',
					url:'chat/receiveSolo',
					headers:{
						authorization:localStorage.getItem("token")
					},
					params:{
						id:this.owner.id
					}
				}).then(
					response=>{
						if(response.data.success){
							this.chatData=response.data.data
						}
					}
				)
			},
			/*修改密码*/
			handlerUpdatePwd(){
				const pwdForm=this.updatePwdForm
				if(pwdForm.oldPwd.length<1||
					pwdForm.newPwd.length<1||
					pwdForm.confirmPwd.length<1){
					this.$message.error('密码不能为空')
					return;
				}
				if(pwdForm.newPwd!==pwdForm.confirmPwd){
					this.$message.error('两次新密码输入不一致！')
				}
				this.$axios({
					method:'POST',
					url:'user/updatePwd',
					headers:{
						authorization:localStorage.getItem("token")
					},
					data:pwdForm
				}).then(
					response=>{
						if(response.data.success){
							this.$message.success("修改成功")
							this.updatePwdVisible=false
						}else{
							this.$message.error(response.data.message)
						}
					},
					error=>{
						console.log(error.message)
					}
				)
				
			},
			GetIconData(){
				this.$axios({
					method:"POST",
					url:'user/getIcons',
					headers:{
						authorization:localStorage.getItem("token")
					},
				}).then(
					response=>{
						if(response.data.success){
							this.iconData=response.data.data
						}else{
							this.$message.error(response.data.message)
						}
					}
				)
			},
			handlerSendRequest(id){
				if(id==this.me.id){
					this.$message.info("这是你自己.. -.-")
					return;
				}
				this.$confirm('是否发送好友请求','提示',{
					confirmButtonText:'确定',
					concelButtonText:'取消',
					type:'warning'
				}).then(
					()=>{			
					this.$axios({
						method:'POST',
						url:'contact/sendRequest',
						headers:{
							authorization:localStorage.getItem("token")
						},
						params:{
							id:id
						}
					}).then(
						response=>{
							if(response.data.success){
								this.$message.success("发送好友请求成功")
							}else{
								this.$message.error(response.data.message)
							}
						},
						error=>{
							console.log(error.message)
						}
					)}).catch(
					()=>{
						this.$message.info('已取消')
					}
				);

			},
			getMessageClass(message){
				if(message.sender===this.me.id){
					return 'chat-message-right'
				}else{
					return 'chat-message-left'
				}
			},
			getMessageIcon(message){
				if(message.sender===this.me.id){
					return this.me.icon
				}else{
					return this.owner.icon
				}
			},
			getOwner(){
				this.$store.dispatch('owner',this.ownerId)
			},
			init(){
				if(this.me.id==this.ownerId){
					this.$store.state.owner=this.me
				}else{
					this.getOwner()
				}
				this.GetIconData();
			}
		},
		mounted(){
			this.init()
			console.log("owenrId-->",this.ownerId)
		},
		beforeDestroy(){
			this.ownerId=null;
		},
		watch:{
			'chatVisible':{
				handler(newVal,oldVal){
					if(newVal){
						this.getChatData();	
						
						this.getChatDataTimer=setInterval(()=>{
							this.getChatData();					
					
						},1000)
					}else{
						clearInterval(this.getChatDataTimer)
					}
				}
			},
			'chatData':{
				handler(newVal,oldVal){
					if(newVal.length>oldVal.length){
						this.$refs.chatMessage.scrollTop=this.$refs.chatMessage.scrollHeight						
					}
				},
				deep:true,
			},
			'ownerId':{
				handler(newVal,oldVal){
					if(newVal!=oldVal){
				if(this.me.id==this.ownerId){
					this.owner=this.me
				}else{
					this.getOwner()
				}
					}
				}
			}
		},
	}
</script>

<style scoped>
.UserInfo{
	height: 350px;
}
.header{
	border-top: 1px solid gray;
	border-bottom: 1px solid gray;
	height: 120px;
}
.header>div{
	display: inline-block;
	height: 100%;
	width: 49%;
	float: left;
}
.username{
	font-size: 30px;
	font-weight: bold;
	color:dodgerblue;
	display: inline-block;
	text-align: center;
	line-height: 110px;
	
}
.body{
	height: 180px;
	width: 100%;
	overflow-y: auto;
	margin: 20px 0px 0px 0 ;
}
.button{
	margin: 5px 10px;
	font-size: 20px;
	width: 90%;
	height: 60px;
}
.icon-box{
	border: 1px solid gray;
	height: 300px;
	overflow-y:auto ;
}
.icon-box>div{
	display: inline-block;
	width: 100px;
	height: 100px;
	margin: 10px 5px;
	text-align: center;
}
.chat-box{
	height: 730px;
	padding: 0 20px;
}
/*聊天消息框*/
.chat-message{
	height: 490px;
	border:1px solid gray;
	overflow-y:auto;
	background: #F8F9FA;
	padding: 0 10px;
	
}
.chat-message>div{
	width: 95%;
	margin: 15px 0;
}
.chat-message>div>div{
	display: inline-block;
}
/*聊天消息内容*/
.chat-message-content{
	border: 1px solid dodgerblue;
	padding: 20px;
	border-radius: 10px;
	max-width: 350px;
	font-size: 17px;
	font-family: "微软雅黑";
	margin-top: 20px;
	color: #000000;
	line-height: 35px;
	background: greenyellow;
}
/*聊天消息时间*/
.chat-message-created{
	font-size: 10px;
	color:gray;
	padding: 0 10px;
}
/*左消息*/
.chat-message-left{
	float: left;
}
/*右消息*/
.chat-message-right{
	float: right;
}
.chat-message-left>.chat-message-icon{
	float: left;
}
.chat-message-right>.chat-message-icon{
	float: right;
}
.chat-message-left>.chat-message-content-box{
	margin-left:10px ;
	float: left;
}
.chat-message-right>.chat-message-content-box{
	margin-right:10px ;
	float: right;
}
.chat-message-left>.chat-message-content-box>.chat-message-created{
	float: left;
}
.chat-message-right>.chat-message-content-box>.chat-message-created{
	float: right;
}
.chat-input{
	margin-top: 15px;
}
.chat-input-button{
	margin-top: 15px;
	float: right;
}
.chat-input-button>button{
	margin: 0 10px;
	width: 100px;
}
</style>